#include "StdAfx.h"
#include "NetworkController.h"
#include "EntityControl.h"
#include "ControlContext.h"



NetworkController::NetworkController(NetworkControlLogic *logic)
{
	controlLogic = logic;

	networkSubsystem = (UltimateNetworkSubsystem*) UltimateSubsystemRegistry::getSingletonPtr()->getSubsystem(NETWORK_SUBSYSTEM);
	networkSubsystem->createRecordForPlayer(logic->getEntityId(), logic->isServerEntity());
}


NetworkController::~NetworkController(void)
{
}

bool NetworkController::isSpawningNeeded()
{
	return false;
}

bool NetworkController::apply(EntityControl* entity, const ControlContext& context)
{

	UltimateNetworkSubsystem::EntityNetworkRecord entityRecord = networkSubsystem->getRecordForPlayer(controlLogic->getEntityId());
	if(entityRecord.entitySpotStatus==UltimateNetworkSubsystem::OTHERS ||entityRecord.entitySpotStatus==UltimateNetworkSubsystem::SERVER_OTHERS )
	{
		entity->setPosition(entityRecord.position);
		entity->setLocalOrientation(entityRecord.orientation);
		if(entityRecord.entityNetworkStatus==UltimateNetworkSubsystem::PLAYING)
		{
			entity->play();
		}

		return false;
	}else if(entityRecord.entitySpotStatus==UltimateNetworkSubsystem::OWN)
	{
		UltimateNetworkSubsystem::EntityNetworkRecord newEntityRecord;
		newEntityRecord.id = controlLogic->getEntityId();
		newEntityRecord.position= entity->getPosition();
		newEntityRecord.orientation= entity->getLocalOrientation();
		newEntityRecord.entitySpotStatus=UltimateNetworkSubsystem::OWN;
		if(entity->isPlaying())
		{
			newEntityRecord.entityNetworkStatus=UltimateNetworkSubsystem::PLAYING;
		}

		networkSubsystem->setRecordForPlayer(controlLogic->getEntityId(), newEntityRecord);
	}

	return true;
}